package com.jie.lanxin.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jie.lanxin.vo.AiImageVO;
import com.jie.lanxin.vo.VivoAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Service
public class AiImageService {

    private final RestTemplate restTemplate; // 用于发送HTTP请求的RestTemplate实例
    private final QueryImageService queryImageService; // 用于查询图像任务状态的服务

    @Autowired
    public AiImageService(RestTemplate restTemplate, QueryImageService queryImageService) {
        this.restTemplate = restTemplate;
        this.queryImageService = queryImageService;
    }

    /**
     * 提交AI图像生成任务
     *
     * @param aiImageVO 包含任务信息的对象
     * @return 查询任务状态的结果
     * @throws UnsupportedEncodingException
     * @throws InterruptedException
     */
    public String taskSubmit(AiImageVO aiImageVO) throws UnsupportedEncodingException, InterruptedException {
        // 认证信息和请求信息
        final String APP_ID = VivoAuth.appId;
        final String APP_KEY = VivoAuth.appKey;
        final String METHOD = "POST";
        final String URI = "/api/v1/task_submit";
        final String DOMAIN = "api-ai.vivo.com.cn";

        // 定义请求体数据
        String styleConfig = aiImageVO.getStyleConfig();
        // 根据不同的风格配置赋值
        if (styleConfig == null) {
            styleConfig = "55c682d5eeca50d4806fd1cba3628781";
        } else if ("GENERAL_V3".equals(styleConfig)) {
            styleConfig = aiImageVO.GENERAL_V3;
        } else if ("GENERAL_V4".equals(styleConfig)) {
            styleConfig = aiImageVO.GENERAL_V4;
        } else if ("FANTASY_ANIME".equals(styleConfig)) {
            styleConfig = aiImageVO.FANTASY_ANIME;
        } else if ("REALISTIC".equals(styleConfig)) {
            styleConfig = aiImageVO.REALISTIC;
        } else if ("CRIMSON_FLAME".equals(styleConfig)) {
            styleConfig = aiImageVO.CRIMSON_FLAME;
        } else if ("COLOR_PAINTED_MANGA".equals(styleConfig)) {
            styleConfig = aiImageVO.COLOR_PAINTED_MANGA;
        }

        // 创建请求体
        Map<String, Object> data = new HashMap<>();
        data.put("height", 768);
        data.put("width", 576);
        data.put("prompt", aiImageVO.getPrompt());
        data.put("styleConfig", styleConfig);

        // 将请求体数据转换为JSON格式
        String requestBody = JSON.toJSONString(data);

        // 请求参数（此处为空）
        Map<String, Object> query = new HashMap<>();
        String queryString = mapToQueryString(query);

        // 生成HTTP头信息
        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryString);
        headers.add("Content-Type", "application/json");

        // 构建请求URL
        String url = String.format("http://%s%s", DOMAIN, URI);
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送请求并获取响应
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Response body: " + response.getBody());
        } else {
            System.out.println("Error response: " + response.getStatusCode());
        }

        // 提取任务ID并查询任务状态
        return queryImageService.queryImage(getTaskIdFromResponse(response.getBody()));
    }

    /**
     * 将Map转换为查询字符串
     *
     * @param map 包含查询参数的Map
     * @return 查询字符串
     */
    private String mapToQueryString(Map<String, Object> map) {
        if (map.isEmpty()) {
            return "";
        }
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (queryStringBuilder.length() > 0) {
                queryStringBuilder.append("&");
            }
            queryStringBuilder.append(entry.getKey());
            queryStringBuilder.append("=");
            queryStringBuilder.append(entry.getValue());
        }
        return queryStringBuilder.toString();
    }

    /**
     * 从响应体中提取任务ID
     *
     * @param responseBody 响应体字符串
     * @return 任务ID
     */
    public static String getTaskIdFromResponse(String responseBody) {
        JSONObject jsonObject = JSON.parseObject(responseBody);
        JSONObject resultObject = jsonObject.getJSONObject("result");
        return resultObject.getString("task_id");
    }
}
